﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Face_Recognition.Haar
{
    public class Feature
    {
        private Rectangle[] rectangles;

        public Rectangle[] Rectangles
        {
            get { return rectangles; }
            set { rectangles = value; }
        }
        public Feature(Rectangle[] rectangles)
        {
            this.Rectangles = rectangles;
        }

        //public Feature(int[][] _rectangles)
        //{
        //    rectangles = _rectangles;
        //}

        public Feature(bool tilted, params int[][] rectangles)
        {
            this.Rectangles = new Rectangle[rectangles.Length];
            for (int i = 0; i < rectangles.Length; i++)
                this.Rectangles[i] = new Rectangle(rectangles[i]);
        }

        public double GetSum(IntegralImage image, int x, int y)
        {
            double sum = 0.0;

           // if (!isTilted)
            {
                // Compute the sum for a standard feature
                foreach (Rectangle rect in Rectangles)
                {
                    sum += image.GetSum(x + rect.ScaledX, y + rect.ScaledY,
                     rect.ScaledWidth, rect.ScaledHeight) * rect.ScaledWeight;
                }
            }


            return sum;
        }

        public void SetScaleAndWeight(float scale, float weight)
        {
            // manual loop unfolding

            if (Rectangles.Length == 2)
            {
                Rectangle a = Rectangles[0];
                Rectangle b = Rectangles[1];

                b.ScaleRectangle(scale);
                b.ScaleWeight(weight);

                a.ScaleRectangle(scale);
                a.ScaledWeight = -(b.Area * b.ScaledWeight) / a.Area;
            }
            else // rectangles.Length == 3
            {
                Rectangle a = Rectangles[0];
                Rectangle b = Rectangles[1];
                Rectangle c = Rectangles[2];

                c.ScaleRectangle(scale);
                c.ScaleWeight(weight);

                b.ScaleRectangle(scale);
                b.ScaleWeight(weight);

                a.ScaleRectangle(scale);
                a.ScaledWeight = -(b.Area * b.ScaledWeight
                    + c.Area * c.ScaledWeight) / (a.Area);
            }
        }

        //public object Clone()
        //{
        //    Rectangle[] newRectangles = new Rectangle[Rectangles.Length];
        //    for (int i = 0; i < newRectangles.Length; i++)
        //    {
        //        Rectangle rect = Rectangles[i];
        //        newRectangles[i] = new Rectangle(rect.X, rect.Y,
        //            rect.Width, rect.Height, rect.Weight);
        //    }

        //    Feature r = new Feature();
        //    r.Rectangles = newRectangles;

        //    return r;
        //}
    }
}
